package cc.mrbird.management.service.impl;

import cc.mrbird.common.domain.QueryRequest;
import cc.mrbird.common.domain.ResponseBo;
import cc.mrbird.common.exception.FileImportException;
import cc.mrbird.common.service.impl.BaseService;
import cc.mrbird.common.util.MD5Utils;
import cc.mrbird.management.dao.ManagementInstitutionsMapper;
import cc.mrbird.management.domain.ManagementInstitutions;
import cc.mrbird.management.service.ManagementInstitutionsService;
import cc.mrbird.system.domain.Dict;
import cc.mrbird.system.domain.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service("managementInstitutionsService")
public class ManagementInstitutionsServiceImpl  extends BaseService<ManagementInstitutions> implements ManagementInstitutionsService {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ManagementInstitutionsMapper managementInstitutionsMapper;

    @Override
    public List<ManagementInstitutions> findManaList(ManagementInstitutions managementInstitutions, QueryRequest request) {
        try {
            Example example = new Example(ManagementInstitutions.class);
            Criteria criteria = example.createCriteria();
            if (StringUtils.isNotBlank(managementInstitutions.getMiName())) {
                criteria.andCondition("mi_name=", managementInstitutions.getMiName());
            }
            if (StringUtils.isNotBlank(managementInstitutions.getAddress())) {
                criteria.andCondition("address=", managementInstitutions.getAddress());
            }
            example.setOrderByClause("id");
            return this.selectByExample(example);
        } catch (Exception e) {
            log.error("error", e);
            return new ArrayList<>();
        }
    }
    @Override
    public ManagementInstitutions findByName(String miName) {
        Example example = new Example(User.class);
        example.createCriteria().andCondition("lower(mi_name)=", miName.toLowerCase());
        List<ManagementInstitutions> list = this.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }
    @Override
    @Transactional
    public void add(ManagementInstitutions managementInstitutions) {
        this.save(managementInstitutions);
    }
    @Override
    public ManagementInstitutions findById(Long id) {
        return this.selectByKey(id);
    }

    @Override
    @Transactional
    public void deleteMana(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        this.batchDelete(list, "id", ManagementInstitutions.class);
    }

    @Override
    public Boolean batchImport(String fileName, MultipartFile file) throws Exception{
        boolean notNull = false;
        List<ManagementInstitutions> ManaList = new ArrayList<ManagementInstitutions>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new FileImportException("上传文件格式不正确");
        }
        boolean isExcel2003 = false;
        if (fileName.matches("^.+\\.(?i)(xls)$")) {
            isExcel2003 = true;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (!isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet!=null){
            notNull = true;
        }
        ManagementInstitutions managementInstitutions;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

            managementInstitutions = new ManagementInstitutions();

            String name = row.getCell(0).getStringCellValue();
            if(name == null || name.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,姓名未填写)");
            }
            String address = row.getCell(1).getStringCellValue();
            if(address==null || address.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,地址未填写)");
            }
            String phoneName = row.getCell(2).getStringCellValue();
            if(phoneName==null ||phoneName.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,联系人未填写)");
            }
            row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
            String phoneTel = row.getCell(3).getStringCellValue();
            if(phoneTel==null ||phoneTel.isEmpty()){
                throw new FileImportException("导入失败(第"+(r+1)+"行,电话未填写)");
            }
            managementInstitutions.setMiName(name);
            managementInstitutions.setAddress(address);
            managementInstitutions.setPhoneName(phoneName);
            managementInstitutions.setPhoneTel(phoneTel);

            ManaList.add(managementInstitutions);
        }
        for (ManagementInstitutions manaResord : ManaList) {
            String mi_name = manaResord.getMiName();
            int cnt = managementInstitutionsMapper.selectByName(mi_name);
            if (cnt == 0) {
                managementInstitutionsMapper.addMana(manaResord);
            } else {
                managementInstitutionsMapper.updateManaByName(manaResord);
            }
        }
        return notNull;
    }

    @Override
    @Transactional
    public void updateMana(ManagementInstitutions managementInstitutions) {
        this.updateNotNull(managementInstitutions);
    }

}
